﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Seguridad.Encriptación;
using System.Web.Security;

namespace LoginCentralizado
{
    public class AutoLogin
    {
        private Encriptador _encriptador;
        private string _passPhrase;
        private string _saltValue;
        private string _hashAlgorithm;
        private int _iterations;
        private string _initVector;
        private int _keySize;

        private Encriptador Encriptador 
        {
            get
            {
                if (_encriptador == null)
                    _encriptador = new Encriptador(_passPhrase, _saltValue, _hashAlgorithm, _iterations, _initVector, _keySize);

                return _encriptador;
            }
        }

        public AutoLogin(string passPhrase, string saltValue, string hashAlgorithm, int iterations, string initVector, int keySize)
        {
            _passPhrase = passPhrase;
            _saltValue = saltValue;
            _hashAlgorithm = hashAlgorithm;
            _iterations = iterations;
            _initVector = initVector;
            _keySize = keySize;
        }

        public void Redirigir(string url)
        {
            try
            {
                string usuario = Encriptador.Encriptar(HttpContext.Current.User.Identity.Name);
                string hora = Encriptador.Encriptar(string.Format("{0}|{1}", DateTime.Now.Hour, DateTime.Now.Minute));
                string query = "?token=" + HttpUtility.HtmlEncode(usuario + ";" + hora);
                string toGo = url + query;
                HttpContext.Current.Response.Redirect(toGo, false);
            }
            catch(Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        private void CorregirValoresQuery(string[] array)
        {
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = array[i].Replace(" ", "+");
            }
        }

        public void Loguear()
        {
            if (HttpContext.Current.Request.QueryString["token"] == null)
                return;

            string token = HttpUtility.HtmlDecode(HttpContext.Current.Request.QueryString["token"]);
            string[] array = token.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            CorregirValoresQuery(array);

            string usuario = Encriptador.Desencriptar(array[0]);
            string hora = Encriptador.Desencriptar(array[1]);
            string[] array2 = hora.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
            DateTime fecha = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(array2[0]), int.Parse(array2[1]), DateTime.Now.Second);
            TimeSpan diferencia = DateTime.Now - fecha;

            if (diferencia.Minutes <= 5)
            {
                FormsAuthentication.Initialize();
                FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, usuario, DateTime.Now, DateTime.Now.AddMinutes(30), false, @"", FormsAuthentication.FormsCookiePath);

                HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(fat)));
            }
            else
                throw new Exception("Token vencido");
        }
    }
}
